﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WH.Model.Enums;
using Rw.Core.Common;
using Rw.Core.Document;
using WH.Common.Handler;
using System.Collections.Generic;
using System.Data;
using System.IO;

namespace WH.WebApi.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class BaseController : ControllerBase
    {
        /// <summary>
        /// access_token
        /// </summary>
        protected string AccessToken
        {
            get
            {
                var token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", string.Empty);
                if (string.IsNullOrWhiteSpace(token))
                {
                    token = HttpContext.Request.Headers["access_token"].ToString();
                }

                if (string.IsNullOrWhiteSpace(token) && HttpContext.Request.Method.ToUpper().Equals("GET"))
                {
                    token = HttpContext.Request.Query["access_token"].ToString();
                }

                if (string.IsNullOrWhiteSpace(token) && HttpContext.Request.Method.ToUpper().Equals("POST"))
                {
                    token = HttpContext.Request.Form["access_token"].ToString();
                }

                return token;
            }
        }

        /// <summary>
        /// 登录信息实体
        /// </summary>
        protected JwtTokenModel LoginDto => JwtTokenHandler.LoginModel;

        /// <summary>
        /// 登录的用户ID
        /// </summary>
        protected string? LoginUserId => JwtTokenHandler.LoginModel.UserId;

        /// <summary>
        /// 登录的用户名或昵称
        /// </summary>
        protected string? LoginUserName => JwtTokenHandler.LoginModel.UserAccount ?? JwtTokenHandler.LoginModel.Name;

        /// <summary>
        /// 登录的用户机构Id
        /// </summary>
        protected string OrganizationId => JwtTokenHandler.LoginModel.OrganizationId;

        ///// <summary>
        ///// 行业
        ///// </summary>
        //protected IndustryEnum Industry => JwtTokenHandler.LoginModel.Industry;

        ///// <summary>
        ///// 场景
        ///// </summary>
        //protected SceneEnum Scene => JwtTokenHandler.LoginModel.Scene;

        /// <summary>
        /// 获取Excel模板
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        protected FileStreamResult GetExcelTemplateFile(string filename)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "assets", "template", filename);
            var fileStream = System.IO.File.OpenRead(path);
            var file = File(fileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename);
            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            return file;
        }

        /// <summary>
        /// 获取Excel
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        protected ResultResponse<DataSet> GetImportExcelDataSet(IFormFile file)
        {
            var result = new ResultResponse<DataSet> { IsSucceed = true };

            var fileName = file.FileName;
            var extension = Path.GetExtension(fileName);
            if (extension == null)
            {
                result.IsSucceed = false;
                result.Msg = "请上传Excel文件";
                return result;
            }

            var ex = extension.ToLower();
            if (ex is not ".xls" and not ".xlsx")
            {
                result.IsSucceed = false;
                result.Msg = "请上传Excel文件";
                return result;
            }

            var stream = file.OpenReadStream();
            var dataSet = ExcelHelper.Read(stream, fileName, true);
            if (dataSet is null)
            {
                result.IsSucceed = false;
                result.Msg = "未读取到Excel数据";
                return result;
            }

            result.Data = dataSet;
            return result;
        }

        /// <summary>
        /// 获取Excel
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        protected FileContentResult GetExportExcel<T>(string filename, IEnumerable<T> data)
        {
            var dataTable = TableHelper.FromEntityWithPropertyDescription(data);
            var excel = ExcelHelper.WriteBytes(new DataTable[] { dataTable }, filename, true);
            var file = File(excel, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename);
            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            return file;
        }

        /// <summary>
        /// 成功
        /// </summary>
        /// <param name="data"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        protected ResultResponse<T> Success<T>(T data, string message = "查询成功")
        {
            return new ResultResponse<T>()
            {
                Code = 200,
                IsSucceed = true,
                Msg = message,
                Data = data
            };
        }

        /// <summary>
        /// 成功
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected ResultResponse Success(string message = "操作成功")
        {
            return new ResultResponse()
            {
                Code = 200,
                IsSucceed = true,
                Msg = message
            };
        }

        /// <summary>
        /// 错误
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected ResultResponse<T> Error<T>(string message = "请求失败")
        {
            Response.StatusCode = 400;
            return new ResultResponse<T>()
            {
                Code = 400,
                IsSucceed = false,
                Msg = message
            };
        }
        /// <summary>
        /// 未授权
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected ResultResponse<T> Unauthorized<T>(string message = "身份认证失败")
        {
            Response.StatusCode = 401;
            return new ResultResponse<T>()
            {
                Code = 401,
                IsSucceed = false,
                Msg = message
            };
        }


        /// <summary>
        /// 错误
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected ResultResponse Error(string message = "操作失败")
        {
            Response.StatusCode = 400;
            return new ResultResponse()
            {
                Code = 400,
                IsSucceed = false,
                Msg = message
            };
        }

        /// <summary>
        /// 错误
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected ResultResponse<T> Exception<T>(string message = "接口错误")
        {
            Response.StatusCode = 500;
            return new ResultResponse<T>()
            {
                Code = 500,
                IsSucceed = false,
                Msg = message
            };
        }
    }
}